package com.zeyi.chat.handler;

import com.alibaba.fastjson.JSON;
import com.zeyi.chat.annotation.Mapping;
import com.zeyi.chat.dto.Chat;
import com.zeyi.chat.dto.Message;
import com.zeyi.chat.manager.SocketManager;
import com.zeyi.chat.service.UserService;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.Socket;
import java.util.List;

/**
 * @author zeyi
 */
public class Dispatcher extends Thread {
    private Socket socket;
    private Integer userId;

    public Dispatcher(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            while (true) {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) ois.readObject();
                Message result = null;
                String[] split = message.getServerPath().split("/");
                Class<?> aClass = Class.forName("com.zeyi.chat.handler." + split[0]);
                try {
                    Method init = aClass.getMethod("getInstance");
                    Method[] methods = aClass.getMethods();
                    for (Method method : methods) {
                        if (method.isAnnotationPresent(Mapping.class)) {
                            Mapping mapping = method.getAnnotation(Mapping.class);
                            if (mapping.value().equals(split[1])) {
                                Type[] parameterTypes = method.getGenericParameterTypes();
                                if (parameterTypes.length > 1) {
                                    if (parameterTypes[1].getTypeName().equals("com.zeyi.chat.handler.Dispatcher")) {
                                        result = (Message) method.invoke(init.invoke(null), message, this);
                                    } else {
                                        result = (Message) method.invoke(init.invoke(null), message, socket);
                                    }
                                } else {
                                    result = (Message) method.invoke(init.invoke(null), message);
                                }
                                break;
                            }
                        }
                    }
                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                if (result != null) {
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject(result);
                }
            }
        } catch (IOException e) {
            SocketManager.removeSocket(userId);
            List<Integer> friendIds = UserService.getInstance().getFriendIds(userId);
            friendIds.forEach(id -> {
                SocketManager.send(id, new Message("ChatHandler/online", JSON.toJSONString(new Chat(userId, false))));
            });
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }
}
